package com.ndood.admin.service.user.impl;

import java.util.Date;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.ndood.admin.core.constaints.AdminErrCode;
import com.ndood.admin.core.exception.AdminException;
import com.ndood.admin.pojo.system.UserPo;
import com.ndood.admin.repository.system.UserRepository;
import com.ndood.admin.service.user.AccountPasswordService;

import lombok.extern.slf4j.Slf4j;

/**
 * 密码管理
 */
@Service
@Slf4j
public class AccountPasswordServiceImpl implements AccountPasswordService{

	@Autowired
	private UserRepository userDao;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Override
	public void changePassword(String userId, String oldPassword, String newPassword) throws AdminException {
	
		log.debug("Setp1: 判断旧密码是否正确");
		Optional<UserPo> option = userDao.findById(Integer.parseInt(userId));
		if(!option.isPresent()) {
			throw new AdminException(AdminErrCode.ERR_PASSWORD, "用户不存在");
		}

		log.debug("Step2: 判断旧密码是否匹配");
		UserPo po = option.get();
		boolean matches = passwordEncoder.matches(po.getPassword(),oldPassword);
		if(!matches) {
			throw new AdminException(AdminErrCode.ERR_PASSWORD, "旧密码错误");
		}
		
		log.debug("Step3: 更新密码");
		po.setPassword(passwordEncoder.encode(newPassword));
		po.setUpdateTime(new Date());
		userDao.save(po);

	}
	
}
